<?php
!defined ('P_W') && exit('Forbidden');

class PW_HouseAreaDB extends BaseDB {

	var $_tableName = "pw_house_area";

	function add($data) {
		$this->_db->update('INSERT INTO ' . $this->_tableName . ' SET ' . pwSqlSingle($data));
	}
	
	function importAreaList($areaList){
		$sql = 'REPLACE INTO ' . $this->_tableName . '(code, name, ifopen) VALUES ' . pwSqlMulti($areaList);
		$this->_db->update($sql);
	}

	function getById($id) {
		return $this->_db->get_one('SELECT * FROM ' . $this->_tableName . ' WHERE id=' . pwEscape($id));
	}

	function deleteByIds($ids) {
		$this->_db->update('DELETE FROM ' . $this->_tableName . ' WHERE id IN (' . pwImplode($ids) . ')');
	}

	function updateByIds($ids, $data) {
		$this->_db->update('UPDATE ' . $this->_tableName . ' SET ' . pwSqlSingle($data) .  ' WHERE id IN (' . pwImplode($ids) . ')');
	}

	function updateById($id, $data) {
		$this->_db->update('UPDATE ' . $this->_tableName . ' SET ' . pwSqlSingle($data) . ' WHERE id=' . pwEscape($id));
	}

	function getByCode($code, $except) {
		$_sql_add = '';
		$except && $_sql_add = ' AND id!=' . pwEscape($except);
		return $this->_db->get_one('SELECT * FROM ' . $this->_tableName . ' WHERE code=' . pwEscape($code) . $_sql_add);
	}
	
	function getAllHouseArea($ifopen = 1){
		if($ifopen) $_where = ' WHERE ifopen = 1 ';
		$sql = 'SELECT * FROM ' . $this->_tableName.$_where ;
		$query = $this->_db->query($sql);
		return $this->_getAllResultFromQuery($query);
	}
	
	function getCountAreaList(){
		$sql = 'SELECT COUNT(*) FROM ' . $this->_tableName;
		return $this->_db->get_value($sql);	
	}
	
	function getAreaList($page,$perpage){
		if (!S::isNum($page) || !S::isNum($perpage)){
			return array();
		} 
		$offset = ($page - 1) * $perpage;
		$sql = 'SELECT * FROM '.$this->_tableName.'  ORDER BY code '.$this->_Limit($offset,$perpage);
		$query = $this->_db->query($sql);
		return  $this->_getAllResultFromQuery($query);
	}
	
	function getAreaListByCode($code,$page,$perpage){
		if (!S::isArray($code) || !S::isNum($page) || !S::isNum($perpage)){
			return array();
		} 
		$offset = ($page - 1) * $perpage;
		$sql = 'SELECT * FROM '.$this->_tableName.'  WHERE code IN (' . pwImplode($code) . ') '.$this->_Limit($offset,$perpage);
		$query = $this->_db->query($sql);
		return  $this->_getAllResultFromQuery($query);
	}
	
	function getAllAreaListByCode($code){
		if (!S::isArray($code)){
			$code = array($code);
		} 
		$sql = 'SELECT * FROM '.$this->_tableName.'  WHERE code IN (' . pwImplode($code) . ') ';
		$query = $this->_db->query($sql);
		return  $this->_getAllResultFromQuery($query);
	}
	
	function getOpenAreaList(){
		$sql = 'SELECT * FROM '.$this->_tableName.' WHERE ifopen=1 ORDER BY code';
		$query = $this->_db->query($sql);
		return  $this->_getAllResultFromQuery($query);
	}
}
?>